package com.fr.web.core.service;

import com.fr.base.CodeUtils;
import com.fr.base.FRContext;
import com.fr.base.StringUtils;
import com.fr.base.core.json.JSONArray;
import com.fr.base.core.json.JSONObject;
import com.fr.base.core.util.vt.VT4FR;
import com.fr.base.core.util.vt.VT4FR.FUNC;
import com.fr.base.dav.Env;
import com.fr.base.file.DatasourceManager;
import com.fr.data.core.db.dialect.Dialect;
import com.fr.data.core.db.dialect.DialectFactory;
import com.fr.data.impl.JDBCDatabaseConnection;
import com.fr.report.web.EmailManager;
import com.fr.schedule.ScheduleContext;
import com.fr.schedule.entry.IdGenerator;
import com.fr.schedule.exception.CreateConnectionException;
import com.fr.schedule.exception.NoSourceException;
import com.fr.schedule.output.EmailNotification;
import com.fr.third.org.quartz.Scheduler;
import com.fr.third.org.quartz.SchedulerException;
import com.fr.third.org.quartz.impl.StdSchedulerFactory;
import com.fr.web.core.WebUtils;
import com.fr.web.platform.entry.EntryManager;
import com.fr.web.platform.tables.PlatTables;
import com.fr.web.platform.tables.QuartzTables;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ScheduleService extends NoSessionIDService
{
  private static ScheduleService SCHEDULE_SERVICE = new ScheduleService();
  public static final String FACTORY_KEY = "com.fr.schedule.StdSchedulerFactory.KEY";
  private boolean performShutdown = true;

  public static ScheduleService getInstance()
  {
    return SCHEDULE_SERVICE;
  }

  public boolean accept(String paramString)
  {
    return paramString.startsWith("fr_schedule_");
  }

  public void process(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse, String paramString)
    throws Exception
  {
    Object localObject1;
    Object localObject2;
    if (paramString == null)
      return;
    PrintWriter localPrintWriter = WebUtils.createPrintWriter(paramHttpServletResponse);
    if ("fr_schedule_getdatanames".equals(paramString))
    {
      JSONArray localJSONArray = new JSONArray();
      localObject2 = FRContext.getDatasourceManager().getConnectionNameIterator();
      while (((Iterator)localObject2).hasNext())
      {
        String str = (String)((Iterator)localObject2).next();
        localJSONArray.put(new JSONObject().put("value", str).put("text", str));
      }
      localPrintWriter.write(CodeUtils.jsonEncode(localJSONArray));
      localPrintWriter.flush();
      localPrintWriter.close();
      return;
    }
    if ("fr_schedule_getdataname".equals(paramString))
    {
      if (StringUtils.isNotBlank(FRContext.getDatasourceManager().getScheduleDatasource()))
      {
        localPrintWriter.write(FRContext.getDatasourceManager().getScheduleDatasource());
        localPrintWriter.flush();
        localPrintWriter.close();
      }
      return;
    }
    if ("fr_schedule_linkname".equals(paramString))
    {
      dealDatasource(paramHttpServletRequest, paramHttpServletResponse);
      return;
    }
    try
    {
      initScheduleServer(paramHttpServletRequest);
    }
    catch (NoSourceException localNoSourceException)
    {
      dealDatasource(paramHttpServletRequest, paramHttpServletResponse);
      return;
    }
    catch (Exception localException)
    {
      FRContext.getLogger().log(Level.WARNING, localException.getMessage(), localException);
      return;
    }
    if ("fr_schedule_setdataname".equals(paramString))
      localPrintWriter.write("success");
    if ("fr_schedule_stopcleardata".equals(paramString))
    {
      clearScheduleData();
      return;
    }
    if ("fr_schedule_file".equals(paramString))
    {
      ExportService.dealScheduleExport(paramHttpServletRequest, paramHttpServletResponse);
      return;
    }
    if (StringUtils.isEmpty(paramString))
      return;
    if ("fr_schedule_getfolder".equals(paramString))
    {
      localObject1 = EntryManager.getFolderEntrys();
      localPrintWriter.print(((JSONArray)localObject1).toString());
    }
    else if ("fr_schedule_getfiles".equals(paramString))
    {
      localObject1 = paramHttpServletRequest.getParameter("folderID");
      localObject2 = EntryManager.getContentEntrys((String)localObject1);
      localPrintWriter.print(((JSONArray)localObject2).toString());
    }
    else if ("fr_schedule_addfolder".equals(paramString))
    {
      localObject1 = WebUtils.getHTTPRequestParameter(paramHttpServletRequest, "folderJason");
      localObject2 = EntryManager.addFolder((String)localObject1);
      localPrintWriter.print(((JSONObject)localObject2).toString());
    }
    else if ("fr_schedule_editfolder".equals(paramString))
    {
      localObject1 = WebUtils.getHTTPRequestParameter(paramHttpServletRequest, "folderJason");
      localObject2 = EntryManager.addFolder((String)localObject1);
      localPrintWriter.print(((JSONObject)localObject2).toString());
    }
    else if ("fr_schedule_delfolder".equals(paramString))
    {
      localObject1 = paramHttpServletRequest.getParameter("folderId");
      EntryManager.deleleFolderByParentId((String)localObject1);
    }
    else if ("fr_schedule_getreport".equals(paramString))
    {
      localObject1 = new IdGenerator();
      localObject2 = EntryManager.getReportletsOfCurrentEnv("reportlets", (IdGenerator)localObject1);
      localPrintWriter.print(((JSONArray)localObject2).toString());
    }
    else if ("fr_schedule_addreport".equals(paramString))
    {
      localObject1 = WebUtils.getHTTPRequestParameter(paramHttpServletRequest, "reportJason");
      localObject2 = EntryManager.addReport((String)localObject1);
      localPrintWriter.print(((JSONObject)localObject2).toString());
    }
    else if ("fr_schedule_delreports".equals(paramString))
    {
      localObject1 = paramHttpServletRequest.getParameter("reportIds");
      EntryManager.delReports((String)localObject1);
    }
    else if ("fr_schedule_addurl".equals(paramString))
    {
      localObject1 = WebUtils.getHTTPRequestParameter(paramHttpServletRequest, "urlJason");
      localObject2 = EntryManager.addURLEntry((String)localObject1);
      localPrintWriter.print(((JSONObject)localObject2).toString());
    }
    else if ("fr_schedule_gettask".equals(paramString))
    {
      localObject1 = paramHttpServletRequest.getParameter("reportId");
      localObject2 = EntryManager.getTasks((String)localObject1);
      localPrintWriter.print(((JSONArray)localObject2).toString());
    }
    else if ("fr_schedule_aoutask".equals(paramString))
    {
      localObject1 = WebUtils.getHTTPRequestParameter(paramHttpServletRequest, "taskJason");
      EntryManager.addOrUpdateTask((String)localObject1);
    }
    else if ("fr_schedule_deltasks".equals(paramString))
    {
      localObject1 = paramHttpServletRequest.getParameter("taskIds");
      EntryManager.delTasks((String)localObject1);
    }
    else if ("fr_schedule_genparameter".equals(paramString))
    {
      localObject1 = paramHttpServletRequest.getParameter("reportPath");
      localObject2 = EntryManager.getParameters((String)localObject1);
      localPrintWriter.print(((JSONArray)localObject2).toString());
    }
    else if ("fr_schedule_statejob".equals(paramString))
    {
      localObject1 = paramHttpServletRequest.getParameter("taskId");
      long l = Long.parseLong((String)localObject1);
      int i = EntryManager.stateJob(l);
      localPrintWriter.print(i);
    }
    else if ("fr_schedule_getemailattr".equals(paramString))
    {
      if (EmailNotification.getEmailManager() == null)
        localPrintWriter.print("FR.i18n.Failed");
      else
        localPrintWriter.print(EmailNotification.getEmailManager().createJSON().toString());
    }
    localPrintWriter.flush();
    localPrintWriter.close();
  }

  public static void dealDatasource(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse)
    throws IOException
  {
    PrintWriter localPrintWriter = WebUtils.createPrintWriter(paramHttpServletResponse);
    localPrintWriter.write("nullSchDS");
    localPrintWriter.flush();
    localPrintWriter.close();
  }

  private synchronized void initScheduleServer(HttpServletRequest paramHttpServletRequest)
    throws Exception
  {
    Connection localConnection;
    if (!(VT4FR.SCHEDULE.support()))
      return;
    DatasourceManager localDatasourceManager = FRContext.getDatasourceManager();
    String str1 = WebUtils.getHTTPRequestParameter(paramHttpServletRequest, "scheduledataname");
    boolean bool = (StringUtils.isEmpty(str1)) ? true : str1.equals(localDatasourceManager.getScheduleDatasource());
    if ((ScheduleContext.getScheduler() != null) && (bool))
      return;
    if ((StringUtils.isNotEmpty(str1)) && (!(str1.equals(localDatasourceManager.getScheduleDatasource()))))
      releaseSchedule();
    if ((StringUtils.isEmpty(localDatasourceManager.getScheduleDatasource())) && (StringUtils.isEmpty(str1)))
      throw new NoSourceException("Need DataSource!");
    if (StringUtils.isNotEmpty(str1))
    {
      localDatasourceManager.setScheduleDatasource(str1);
      FRContext.getCurrentEnv().writeResource(localDatasourceManager);
      ScheduleContext.refreshDatabaseConnection();
    }
    JDBCDatabaseConnection localJDBCDatabaseConnection = (JDBCDatabaseConnection)localDatasourceManager.getConnection(localDatasourceManager.getScheduleDatasource());
    try
    {
      localConnection = localJDBCDatabaseConnection.createConnection();
    }
    catch (Exception localException1)
    {
      throw new CreateConnectionException("Connection create Error!");
    }
    Dialect localDialect = DialectFactory.generateDialect(localConnection);
    createScheduleTables(localConnection);
    try
    {
      localConnection.close();
    }
    catch (SQLException localSQLException)
    {
      FRContext.getLogger().log(Level.WARNING, localSQLException.getMessage(), localSQLException);
    }
    ServletContext localServletContext = paramHttpServletRequest.getSession().getServletContext();
    try
    {
      StdSchedulerFactory localStdSchedulerFactory;
      String str2 = localServletContext.getInitParameter("config-file");
      String str3 = localServletContext.getInitParameter("shutdown-on-unload");
      if (str3 != null)
        this.performShutdown = Boolean.valueOf(str3).booleanValue();
      if (str2 != null)
      {
        localStdSchedulerFactory = new StdSchedulerFactory(str2);
      }
      else
      {
        localObject = new Properties();
        initProperties((Properties)localObject);
        ((Properties)localObject).put("com.fr.third.org.quartz.dataSource.myDS.URL", localJDBCDatabaseConnection.getURL());
        ((Properties)localObject).put("com.fr.third.org.quartz.dataSource.myDS.driver", localJDBCDatabaseConnection.getDriver());
        ((Properties)localObject).put("com.fr.third.org.quartz.dataSource.myDS.user", localJDBCDatabaseConnection.getUser());
        ((Properties)localObject).put("com.fr.third.org.quartz.dataSource.myDS.password", localJDBCDatabaseConnection.getPassword());
        ((Properties)localObject).put("com.fr.third.org.quartz.jobStore.driverDelegateClass", localDialect.quartzDelegateClass());
        localStdSchedulerFactory = new StdSchedulerFactory((Properties)localObject);
      }
      ScheduleContext.setScheduler(localStdSchedulerFactory.getScheduler());
      Object localObject = localServletContext.getInitParameter("start-scheduler-on-load");
      int i = 0;
      String str4 = localServletContext.getInitParameter("start-delay-seconds");
      try
      {
        if ((str4 != null) && (str4.trim().length() > 0))
          i = Integer.parseInt(str4);
      }
      catch (Exception localException3)
      {
        FRContext.getLogger().log(Level.WARNING, "Cannot parse value of 'start-delay-seconds' to an integer: " + str4 + ", defaulting to 5 seconds.");
        i = 5;
      }
      if ((localObject == null) || (Boolean.valueOf((String)localObject).booleanValue()))
        if (i <= 0)
        {
          ScheduleContext.getScheduler().start();
          FRContext.getLogger().log(Level.WARNING, "Scheduler has been started...");
        }
        else
        {
          ScheduleContext.getScheduler().startDelayed(i);
          FRContext.getLogger().log(Level.WARNING, "Scheduler will start in " + i + " seconds.");
        }
      else
        FRContext.getLogger().log(Level.WARNING, "Scheduler has not been started. Use scheduler.start()");
      String str5 = localServletContext.getInitParameter("servlet-context-factory-key");
      if (str5 == null)
        str5 = "com.fr.schedule.StdSchedulerFactory.KEY";
      FRContext.getLogger().log(Level.WARNING, "Storing the FineReport Scheduler Factory in the servlet context at key: " + str5);
      localServletContext.setAttribute(str5, localStdSchedulerFactory);
    }
    catch (Exception localException2)
    {
      FRContext.getLogger().log(Level.WARNING, localException2.getMessage(), localException2);
    }
  }

  private static void releaseSchedule()
  {
    if (ScheduleContext.getScheduler() != null)
    {
      try
      {
        ScheduleContext.getScheduler().shutdown();
      }
      catch (SchedulerException localSchedulerException)
      {
        FRContext.getLogger().log(Level.WARNING, localSchedulerException.getMessage(), localSchedulerException);
        return;
      }
      ScheduleContext.setScheduler(null);
      FRContext.getLogger().log(Level.WARNING, "FineReport Scheduler has been shutdown successfully!");
    }
  }

  private void createScheduleTables(Connection paramConnection)
  {
    QuartzTables localQuartzTables = new QuartzTables();
    PlatTables localPlatTables = new PlatTables();
    localQuartzTables.generatorModuleTables(paramConnection);
    localPlatTables.generatorModuleTables(paramConnection);
  }

  private void removeScheduleTables(Connection paramConnection)
  {
    QuartzTables localQuartzTables = new QuartzTables();
    PlatTables localPlatTables = new PlatTables();
    localQuartzTables.removeModuleTables(paramConnection);
    localPlatTables.removeModuleTables(paramConnection);
  }

  private void clearScheduleData()
  {
    releaseSchedule();
    DatasourceManager localDatasourceManager = FRContext.getDatasourceManager();
    JDBCDatabaseConnection localJDBCDatabaseConnection = (JDBCDatabaseConnection)localDatasourceManager.getConnection(localDatasourceManager.getScheduleDatasource());
    Connection localConnection = null;
    try
    {
      localConnection = localJDBCDatabaseConnection.createConnection();
    }
    catch (Exception localException1)
    {
      FRContext.getLogger().log(Level.WARNING, localException1.getMessage(), localException1);
      return;
    }
    removeScheduleTables(localConnection);
    try
    {
      localConnection.close();
    }
    catch (SQLException localSQLException)
    {
      FRContext.getLogger().log(Level.WARNING, localSQLException.getMessage(), localSQLException);
    }
    localDatasourceManager.setScheduleDatasource(null);
    try
    {
      FRContext.getCurrentEnv().writeResource(localDatasourceManager);
    }
    catch (Exception localException2)
    {
      FRContext.getLogger().log(Level.WARNING, localException2.getMessage(), localException2);
    }
  }

  private void initProperties(Properties paramProperties)
  {
    paramProperties.put("com.fr.third.org.quartz.jobStore.class", "com.fr.third.org.quartz.impl.jdbcjobstore.JobStoreTX");
    paramProperties.put("com.fr.third.org.quartz.jobStore.dataSource", "myDS");
    paramProperties.put("com.fr.third.org.quartz.dataSource.myDS.maxConnections", "5");
    paramProperties.put("com.fr.third.org.quartz.jobStore.isClustered", new Boolean(false));
    paramProperties.put("com.fr.third.org.quartz.jobStore.tablePrefix", "QRTZ_");
    paramProperties.put("com.fr.third.org.quartz.jobStore.useProperties", new Boolean(false));
    paramProperties.put("com.fr.third.org.quartz.threadPool.class", "com.fr.third.org.quartz.simpl.SimpleThreadPool");
    paramProperties.put("com.fr.third.org.quartz.threadPool.threadCount", "10");
  }
}